package ycl.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import ycl.common.result.REnum;
import ycl.common.result.Result;
import ycl.common.utils.ServletUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败
 *
 * @author ycl
 * @date 2022-03-10 10:59:09
 */
@Slf4j
@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(
			HttpServletRequest request,
			HttpServletResponse response,
			AuthenticationException e) throws IOException {
		log.info("AuthFailHandler . onAuthenticationFailure . 认证检查失败");

		Result<Object> result;
		if (e instanceof CredentialsExpiredException) {
			//凭证过期
			result = Result.fail(REnum.CUSTOM_TEMP_PASSWORD);
		} else {
			log.error("{}", e.getMessage());
			result = Result.fail(e.getMessage());
		}
		ServletUtil.writeResponse(response, result);
	}
}
